package controllers

import (
	user "HomeStation/db"
	"crypto/md5"
	"fmt"
	"time"

	"github.com/astaxie/beego/orm"
	"github.com/beego/beego/v2/server/web"
)

var session_user_id = "user_id"
var login_cookies_state = "user_cookies"

///通过session 获取到用户信息
func CheckUserOfSession(controller *web.Controller) *user.User {
	user_id := controller.GetSession(session_user_id)
	fmt.Printf("session %v", user_id)
	if nil == user_id {
		return nil
	}
	users := user.User{Id: user_id.(int)}

	o := orm.NewOrm()
	if err := o.Read(&users); nil == err {
		return &users
	} else {
		fmt.Println(err)
	}

	return nil
}

///设置用户session
func SetSession(controller *web.Controller, session interface{}) {
	controller.SetSession(session_user_id, session)
	data := []byte(time.Now().String())
	cookies := fmt.Sprintf("%x", md5.Sum(data))
	controller.Ctx.SetCookie(login_cookies_state, cookies)
}
